<script setup lang="ts">
import { getEnvironmentList } from '@/api/code/environment';
import { Environment } from '@/api/code/environment/type';
import { Numeric } from 'vant/lib/utils';
import { onMounted, Ref, ref } from 'vue';

const environment = defineModel() as Ref<Environment>;
const showEnvironment = ref(false);
const environmentList = ref([] as Environment[]);
const pickerValue = ref<Numeric[]>([]);
const columns = ref([] as {
    text: string, value: string
}[]);
const loading = ref(true);

onMounted(async () => {
    try {
        const res = await getEnvironmentList();
        environmentList.value = res.data;
        
        environmentList.value.forEach((item, index) => {
            columns.value.push({
                text: item.name,
                value: index.toString()
            });
        });
    } catch (error) {
        console.error('加载环境类型列表失败:', error);
    } finally {
        loading.value = false;
    }
})

const onConfirm = (data : { selectedValues: number, selectedOptions: string}) => {
    showEnvironment.value = false;
    environment.value = environmentList.value[data.selectedValues];
}
</script>

<template>
    <div>
        <van-field
            v-model="environment.name"
            is-link
            readonly
            label="环境类型"
            placeholder="请选择环境类型"
            @click="showEnvironment = true"
            :rules="[{ required: true, message: '请选择环境类型' }]"
            :loading="loading"
        />
        <van-popup v-model:show="showEnvironment" destroy-on-close round position="bottom">
            <div class="picker-header">
                <div class="picker-title">选择环境类型</div>
            </div>
            <van-picker
                :model-value="pickerValue"
                :columns="columns"
                @cancel="showEnvironment = false"
                @confirm="onConfirm"
                :loading="loading"
            />
        </van-popup>
    </div>
</template>

<style lang="scss" scoped>
.picker-header {
    padding: 16px;
    text-align: center;
    border-bottom: 1px solid #f2f3f5;
    
    .picker-title {
        font-size: 16px;
        font-weight: 500;
        color: #323233;
    }
}
</style>